package com.namo.cchfile.controller;

import com.namo.cchcommon.api.CommonResult;
import com.namo.cchcommon.api.ResultCode;
import com.namo.cchcommon.exception.ApiException;
import com.namo.cchfile.entity.FileEntity;
import com.namo.cchfile.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author WangXin
 * @date 2021/3/31 10:55
 */
@RestController
@RequestMapping("/pic")
@Slf4j
public class FileController {

    @Autowired
    FileService fileService;
    /**
     * 上传文件
     * @param file    文件主体
     * @param quality 图片质量 quality  (0.0-1.0)
     * @param expiry  过期时间 expiry (ms)
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public CommonResult upload(@RequestParam("file") MultipartFile file, @RequestParam(value = "quality", required = false) String quality, @RequestParam(name = "expiry", required = false) String expiry) {
        //设置默认值
        if (quality == null) {
            quality = "1.0";
        }
        if (expiry == null) {
            expiry = "0";
        }
        FileEntity fileEntity = null;
        try {
            fileEntity = fileService.uploadFile(file, Double.valueOf(quality), Integer.valueOf(expiry));
        } catch (NumberFormatException e) {
            log.error("请求参数错误--------" + e.getMessage());
            throw new ApiException(500L, "请求参数错误");
        }
        return CommonResult.success(fileEntity);
    }

    /**
     * 删除文件
     *
     * @param objectName 对象名，支持模糊删除（仅对象名或者路径）
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public CommonResult delete(@RequestParam("object_name") String objectName) {
        fileService.delete(objectName);
        return CommonResult.success(null);
    }

    /**
     * 查看对象列表
     * @return
     */
    @RequestMapping(value = "/getfiles",method = RequestMethod.GET)
    public CommonResult getFiles(){
        return null;
    }
}
